package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;
    // 分页查询
    @Override
    public PageResult pageQuery(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        //1.设置分页参数
        Page<Clazz> pageInfo = new Page<>(page, pageSize);
        //2.构造查询条件
        LambdaQueryWrapper<Clazz> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null && !name.isEmpty(), Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getEndDate, begin, end);
        Page<Clazz> paged = page(pageInfo, wrapper);
        List<Emp> emps = empService.list();
        List<Clazz> clazzList = paged.getRecords();

        for (Emp emp : emps) {
            clazzList.forEach(clazz -> {
                if (Objects.equals(clazz.getMasterId(), emp.getId())) {
                    clazz.setMasterName(emp.getName());
                }
                LocalDate now = LocalDate.now();
                if (now.isAfter(clazz.getBeginDate()) && now.isBefore(clazz.getEndDate())) {
                    clazz.setStatus("开课中");
                } else if (now.isBefore(clazz.getBeginDate())) {
                    clazz.setStatus("未开始");
                } else {
                    clazz.setStatus("已结束");
                }
            });
        }

        PageResult pageResult = new PageResult(paged.getTotal(), paged.getRecords());
        return pageResult;
    }
}
